using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using YB.EnterpriseLibrary.XSLTManager.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.ObjectBuilder2;
using System.Xml.Xsl;

namespace YB.EnterpriseLibrary.XSLTManager
{
    class XSLTManagerCustomFactory : ICustomFactory
    {
        #region ICustomFactory Members

        public object CreateObject(IBuilderContext context, string name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            XSLTManagerData objectConfiguration = GetConfiguration(name, configurationSource);

            XSLTManager createdObject = BuildXSLTManager(objectConfiguration);
            RegisterObject(context, name, createdObject);

            return createdObject;
        }

        #endregion

        public XSLTManager BuildXSLTManager(XSLTManagerData data)
        {
            XsltSettings settings = new XsltSettings();
            settings.EnableDocumentFunction = data.EnableDocumentFunction;
            settings.EnableScript = data.EnableScript;
            XslCompiledTransform xslt = new XslCompiledTransform(data.Debug);
            string text;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(data.Url))
            {
                text = sr.ReadToEnd();
            }
            xslt.Load(data.Url, settings, null);
            XSLTManager xsltManager = new XSLTManager(data.Name, data.MimeType, xslt, text);
            return xsltManager;
        }

        private static XSLTManagerData GetConfiguration(string id, IConfigurationSource configurationSource)
        {
            XSLTManagerConfigurationView view = new XSLTManagerConfigurationView(configurationSource);
            return view.GetXSLTManagerData(id);
        }

        private static void RegisterObject(IBuilderContext context, string name, XSLTManager createdObject)
        {

            if (context.Locator != null)
            {
                context.Locator.Add(new NamedTypeBuildKey(typeof(XSLTManager), name), createdObject);
            }
            if (context.Lifetime != null)
            {
                context.Lifetime.Add(createdObject);
            }
        }
    }
}
